package com.phpxiu.app.kkylive.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.event.WeiXinEvent;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpCallback;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.BaseLogin;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

import de.greenrobot.event.EventBus;


/**
 * @file
 * @brief  微信授权、分享回调界面
 * @author 吴金洲
 * @note 微信授权、分享回调界面
 *
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    public final static String TAG="WXEntryActivity";
	public final static int TIMELINE_SUPPORTED_VERSION = 0x21020001;//支持朋友圈的版本号
    private final static String API_GET_TOKEN="https://api.weixin.qq.com/sns/oauth2/access_token?";//取得接口使用凭证
    private final static String API_REFRESH_TOKEN="https://api.weixin.qq.com/sns/oauth2/refresh_token?";//刷新凭证
    private final static String API_GET_USER="https://api.weixin.qq.com/sns/userinfo?";//获取用户信息
    public final static Gson gson=new Gson();
    public static IWXAPI api;

    private static String authCode;
    private static String refreshToken;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(api==null) {
            api= KKYApp.mWeiXinAPI;
        }
        api.handleIntent(getIntent(), this);
    }

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
        api.handleIntent(intent, this);
	}


	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
		    case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:

			    break;
		    case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
			    break;
		    default:
			    break;
		}
	}

	@Override
	public void onResp(BaseResp resp) {
        if(resp instanceof SendAuth.Resp) {
            SendAuth.Resp authResp=(SendAuth.Resp)resp;
            switch (authResp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    //1.微信用户同意授权
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "微信用户同意授权", Toast.LENGTH_LONG).show();
                    }
                    authCode=authResp.code;
                    if(authCode==null){
                        EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                        if(KKYUtil.DEBUG) {
                            Toast.makeText(WXEntryActivity.this, "微信客户端授权码返回空", Toast.LENGTH_LONG).show();
                        }
                        boolean reAuth=true;//重新拉起微信app授权
                        if(reAuth) {
                            // send oauth request
                            final SendAuth.Req req = new SendAuth.Req();
                            req.scope = "snsapi_userinfo";
                            req.state = "5227311980";//传随机数
                            //api.sendReq(req);
                        }
                        return;
                    }
                    //2.获取接口调用凭证
                    StringBuffer tokenApi=new StringBuffer(API_GET_TOKEN);
                    tokenApi.append("appid=").append(BaseLogin.WX_APP_ID).append("&");
                    tokenApi.append("secret=").append(BaseLogin.WX_APP_SECRET).append("&");
                    tokenApi.append("code=").append(authCode).append("&");
                    tokenApi.append("grant_type=").append("authorization_code");
                    OKHttp.get(tokenApi.toString(),TAG,new OKHttpCallback(true) {
                        @Override
                        public void onSuccess(String body) {
                            KKYUtil.log(TAG, "获取微信凭证(access_token)结果:" + body);
                            refreshToken=null;
                            if(body!=null) {
                                WXAuthInfo authInfo = null;
                                try {
                                    authInfo = gson.fromJson(body, WXAuthInfo.class);
                                } catch (JsonParseException e) {
                                    EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                                    if (KKYUtil.DEBUG) {
                                        Toast.makeText(WXEntryActivity.this, "获取微信凭证失败...", Toast.LENGTH_LONG).show();
                                    }
                                }
                                if (authInfo != null) {
                                    if (authInfo.getErrcode() != null) {
                                        //errCode==40029,表示access_token失效
                                        if (KKYUtil.DEBUG) {
                                            Toast.makeText(WXEntryActivity.this, "获取微信凭证失败:" + authInfo.getErrcode() + "@" + authInfo.getErrmsg(), Toast.LENGTH_LONG).show();
                                        }
                                        if (authInfo.getErrcode().equals("40029")) {
                                            //refreshToken();//凭证过期，刷新或续期
                                            EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                                        }
                                    } else {
                                        refreshToken = authInfo.getRefresh_token();
                                        if (KKYUtil.DEBUG) {
                                            Toast.makeText(WXEntryActivity.this, "获取微信接口调用凭证(access_token)成功：openid==" + authInfo.getOpenid(), Toast.LENGTH_LONG).show();
                                        }
                                        getUserInfo(authInfo.getAccess_token(), authInfo.getOpenid());
                                    }
                                } else {
                                    EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                                    if (KKYUtil.DEBUG) {
                                        Toast.makeText(WXEntryActivity.this, "获取微信凭证", Toast.LENGTH_LONG).show();
                                    }
                                }
                            }
                            finish();
                        }

                        @Override
                        public void onErr(String errMsg) {
                            EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                            refreshToken=null;
                            if(KKYUtil.DEBUG) {
                                Toast.makeText(WXEntryActivity.this,"获取微信凭证失败:"+errMsg, Toast.LENGTH_LONG).show();
                            }
                            KKYUtil.log(TAG, errMsg);
                            finish();
                        }
                    });
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                    authCode=null;
                    refreshToken=null;
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "微信用户取消授权", Toast.LENGTH_LONG).show();
                    }
                    finish();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                    authCode=null;
                    refreshToken=null;
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "微信用户拒绝授权", Toast.LENGTH_LONG).show();
                    }
                    finish();
                    break;
                default:
                    break;
            }
        }else{
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "微信用户分享成功", Toast.LENGTH_LONG).show();
                    }
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "微信用户分享取消", Toast.LENGTH_LONG).show();
                    }
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "微信用户分享拒绝", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
            EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.SHARE));
            finish();
        }
	}

    /**
     * access_token失效，刷新或续有效期
     */
    private void refreshToken(){
        if(authCode==null||refreshToken==null){
            return;
        }
        StringBuffer refreshTokenApi=new StringBuffer(API_REFRESH_TOKEN);
        refreshTokenApi.append("appid=").append(BaseLogin.WX_APP_ID).append("&");
        refreshTokenApi.append("refresh_token=").append(refreshToken).append("&");
        refreshTokenApi.append("code=").append(authCode).append("&");
        refreshTokenApi.append("grant_type=").append("refresh_token");
        OKHttp.get(refreshToken.toString(),TAG,new OKHttpCallback(true) {
            @Override
            public void onSuccess(String body) {
                KKYUtil.log(TAG, "刷新微信接口调用凭证(access_token)结果:" + body);
                finish();
                if(body!=null){
                    WXAuthInfo authInfo=null;
                    try {
                        authInfo=gson.fromJson(body,WXAuthInfo.class);
                    }catch (JsonParseException e){
                        EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                        if(KKYUtil.DEBUG) {
                            Toast.makeText(WXEntryActivity.this, "刷新微信接口调用凭证(access_token)结果解析异常", Toast.LENGTH_LONG).show();
                        }
                    }
                    if(authInfo!=null){
                        if(authInfo.getErrcode()!=null){
                            EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                            //errCode==40030,表示refresh_token也失效
                            refreshToken=null;
                            if(KKYUtil.DEBUG) {
                                Toast.makeText(WXEntryActivity.this, "刷新微信接口调用凭证(access_token)错误：errCode：" + authInfo.getErrcode() + "@" + authInfo.getErrmsg(), Toast.LENGTH_LONG).show();
                            }
                        }else{
                            if(KKYUtil.DEBUG) {
                                Toast.makeText(WXEntryActivity.this, "刷新微信接口调用凭证(access_token)成功：openid==" + authInfo.getOpenid(), Toast.LENGTH_LONG).show();
                            }
                        }
                    }else{
                        EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                        if(KKYUtil.DEBUG) {
                            Toast.makeText(WXEntryActivity.this, "刷新微信接口调用凭证(access_token)失败：authInfo is null", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }

            @Override
            public void onErr(String errMsg) {
                EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                if(KKYUtil.DEBUG) {
                    Toast.makeText(WXEntryActivity.this, "刷新微信接口调用凭证(access_token)失败：authInfo is null", Toast.LENGTH_LONG).show();
                }
                KKYUtil.log(TAG, errMsg);
                finish();
            }
        });
    }

    /**
     * 获取用户信息
     */
     private void getUserInfo(String accessToken,String openId){
         StringBuffer getUserApi=new StringBuffer(API_GET_USER);
         getUserApi.append("access_token=").append(accessToken).append("&");
         getUserApi.append("openid=").append(openId);
         OKHttp.get(getUserApi.toString(),TAG,new OKHttpCallback(true) {
             @Override
             public void onSuccess(String body) {
                 KKYUtil.log(TAG, "获取微信用户信息结果:" + body);
                 if(body!=null){
                     WXUserInfo userInfo=null;
                     try {
                         userInfo=gson.fromJson(body,WXUserInfo.class);
                     }catch (JsonParseException e){
                         EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                         if(KKYUtil.DEBUG) {
                             Toast.makeText(WXEntryActivity.this, "获取微信用户信息结果结果解析异常", Toast.LENGTH_LONG).show();
                         }
                     }
                     if(userInfo!=null){
                         if(userInfo.getErrcode()!=null){
                             //errCode==40030,表示refresh_token也失效
                             refreshToken=null;
                             EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                             if(KKYUtil.DEBUG) {
                                 Toast.makeText(WXEntryActivity.this, "获取微信用户信息结果错误：errCode：" + userInfo.getErrcode() + "@" + userInfo.getErrmsg(), Toast.LENGTH_LONG).show();
                             }
                         }else{
                             if(KKYUtil.DEBUG) {
                                 Toast.makeText(WXEntryActivity.this, "获取微信用户信息成功：userName==" + userInfo.getNickname(), Toast.LENGTH_LONG).show();
                             }
                             EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_SUCCESS,userInfo.getUnionid(),userInfo.getOpenid(),userInfo.getOpenid(),userInfo.getNickname()));
                         }
                     }else{
                         EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
                         if(KKYUtil.DEBUG) {
                             Toast.makeText(WXEntryActivity.this, "获取微信用户信息失败：authInfo is null", Toast.LENGTH_LONG).show();
                         }
                     }
                 }
             }

             @Override
             public void onErr(String errMsg) {
                 EventBus.getDefault().post(new WeiXinEvent(WeiXinEvent.LOGIN_ERR));
             }
         });
    }
}